﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WinnerCMS.Common.MemcachedClient;
using WinnerCMS.Common;
namespace WinnerCMS.CacheStorager
{
    public sealed class MemCachedManager
    {
        #region 静态方法和属性
        private static MemcachedClient _mc;
        private static MemcachedConfig _memCachedConfigInfo;
        private static SockIOPool _pool;
         
        #endregion

        static MemCachedManager()
        {
            CreateManager();
        }
        private static readonly object SyncRoot = new Object();
         
        private static void CreateManager()
        {
            if (_memCachedConfigInfo == null)
            {
                lock (SyncRoot)
                {
                    if (_memCachedConfigInfo == null)
                    {
                        _memCachedConfigInfo = SerializableHelper.DeSerialize<MemcachedConfig>(new FileInfo(HttpServer.MapPath("~\\Config\\WinnerCMS.Memcached.config")));

                        if (_memCachedConfigInfo == null)
                        {
                            throw new ArgumentNullException("反序列化出错。");
                        }
                    }
                }
            }
             

            _pool = SockIOPool.GetInstance(_memCachedConfigInfo.PoolName);
            _pool.SetServers(_memCachedConfigInfo.ServerList);
            _pool.InitConnections = _memCachedConfigInfo.InitConnections;//初始化链接数
            _pool.MinConnections = _memCachedConfigInfo.MinConnections;//最少链接数
            _pool.MaxConnections = _memCachedConfigInfo.MaxConnections;//最大连接数
            _pool.SocketConnectTimeout = _memCachedConfigInfo.SocketConnectTimeout;//Socket链接超时时间
            _pool.SocketTimeout = _memCachedConfigInfo.SocketTimeout;// Socket超时时间
            _pool.MaintenanceSleep = _memCachedConfigInfo.MaintenanceSleep;//维护线程休息时间
            _pool.Failover = _memCachedConfigInfo.Failover; //失效转移(一种备份操作模式)
            _pool.Nagle = _memCachedConfigInfo.Nagle;//是否用nagle算法启动socket
            _pool.HashingAlgorithm = HashingAlgorithm.NewCompatibleHash;
            _pool.Initialize();


            _mc = new MemcachedClient();
            _mc.PoolName = _memCachedConfigInfo.PoolName;
            _mc.EnableCompression = _memCachedConfigInfo.EnableCompression;
        }

    
        /// <summary>
        /// 客户端缓存操作对象
        /// </summary>
        public static MemcachedClient CacheClient
        {
            get
            {
                if (_mc == null)
                    CreateManager();

                return _mc;
            }
        }

        public static void Shutdown()
        {
            if (_pool != null)
                _pool.Shutdown();
        }
    }
}